package com.beiming.libra.common.utils;

import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

/**
 * @Author: chenjt
 * @Description: 生成word工具类
 * @Date: Created 2018-05-04 11:59
 */

@Slf4j
@Component
public class FreeMarkerUtil {

  private static String docxAndFtl;

  @Value("${notary.adjustBook.docxAndFtl}")
  public void setDocxAndFtl(String docxAndFtl) {
    FreeMarkerUtil.docxAndFtl = docxAndFtl;
  }

  public static boolean outNotarizationFile(String tempFilePath, String finalFilePath, String tempFileName, Map<String, Object> dataMap) {
    try {
      /** 初始化配置文件 **/
      Configuration configuration = new Configuration();
      /** 设置编码 **/
      configuration.setDefaultEncoding("utf-8");
      String fileDirectory = ResourceUtils.getFile(docxAndFtl).getAbsolutePath();
      String docxTemplate = ResourceUtils.getFile(docxAndFtl + File.separator + tempFileName + ".docx").getAbsolutePath();
      /** 加载文件 **/
      configuration.setDirectoryForTemplateLoading(new File(fileDirectory));
      /** 加载模板 **/
      Template template = configuration.getTemplate(tempFileName + ".ftl");
      /** 指定输出word文件的路径 **/
      FileOutputStream fos = new FileOutputStream(new File(tempFilePath));
      Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
      template.process(dataMap, out);
      if (out != null) {
        out.close();
      }
      XmlToDocxUtil docx = new XmlToDocxUtil();
      docx.outDocx(new File(tempFilePath), docxTemplate, finalFilePath);
    } catch (Exception e) {
      log.error("outNotarizationFile 生成文档失败!, 使用的模板名是: " + tempFileName);
      return false;
    }
    log.info("outNotarizationFile 生成文档成功!, 使用的模板名是: " + tempFileName);
    return true;
  }


}
